package com.ksy.common.image;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.ksy.common.R;
import com.ksy.common.activity.CommonBaseActivity;
import com.ksy.common.utils.AndroidUtil;
import com.ksy.common.utils.PermissionUtils;
import com.ksy.common.view.GridOffsetsItemDecoration;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ImagePickActivity extends CommonBaseActivity {
    private final int Code_Permission = 991;
    private final int Code_Capture = 992;
    public static final String Data_selectImages = "Data_selectImages";
    public static final String Data_isMulti = "Data_isMulti";
    public static final String Data_maxChoose = "Data_maxChoose";
    private ImageView back;
    private TextView des;
    private TextView enter;
    private RecyclerView recycler;
    private RelativeLayout bottom;
    private RelativeLayout folder;
    private TextView folderName;
    private TextView preview;
    private List<ImageFolder> allImageFolders = new ArrayList<>();
    private List<ImageItem> allImages = new ArrayList<>();

    private ImageItemAdapter imageItemAdapter;
    private View folderChooseView;
    private RecyclerView recyclerFolder;
    private ImageFolderAdapter folderAdapter;
    private View spacer;
    private boolean isMulti;
    private File tempImageFile;
    private int maxChoose;
    private int mImageSize;
    interface DataLoadListener {
        void loadFinish(ArrayList<ImageFolder> imageFolders);
    }

    private class ImageLoad implements LoaderManager.LoaderCallbacks<Cursor> {
        private final FragmentActivity activity;
        private final DataLoadListener loadListener;
        private ArrayList<ImageFolder> imageFolders = new ArrayList<>();   //所有的图片文件夹
        private final String[] IMAGE_PROJECTION = {     //查询图片需要的数据列
                MediaStore.Images.Media.DISPLAY_NAME,   //图片的显示名称  aaa.jpg
                MediaStore.Images.Media.DATA,           //图片的真实路径  /storage/emulated/0/pp/downloader/wallpaper/aaa.jpg
                MediaStore.Images.Media.SIZE,           //图片的大小，long型  132492
                MediaStore.Images.Media.WIDTH,          //图片的宽度，int型  1920
                MediaStore.Images.Media.HEIGHT,         //图片的高度，int型  1080
                MediaStore.Images.Media.MIME_TYPE,      //图片的类型     image/jpeg
                MediaStore.Images.Media.DATE_ADDED};    //图片被添加的时间，long型  1450518608

        public ImageLoad(FragmentActivity activity, final DataLoadListener loadListener) {
            this.activity = activity;
            this.loadListener = loadListener;
            LoaderManager loaderManager = activity.getSupportLoaderManager();
            loaderManager.initLoader(0, null, this);
        }

        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
            CursorLoader cursorLoader = new CursorLoader(activity, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION, null, null, IMAGE_PROJECTION[6] + " DESC");
            return cursorLoader;
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
            imageFolders.clear();
            if (data != null) {
                ArrayList<ImageItem> allImages = new ArrayList<>();   //所有图片的集合,不分文件夹
                while (data.moveToNext()) {
                    //查询数据
                    String imageName = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]));
                    String imagePath = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[1]));

                    File file = new File(imagePath);
                    if (!file.exists() || file.length() <= 0) {
                        continue;
                    }

                    long imageSize = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[2]));
                    int imageWidth = data.getInt(data.getColumnIndexOrThrow(IMAGE_PROJECTION[3]));
                    int imageHeight = data.getInt(data.getColumnIndexOrThrow(IMAGE_PROJECTION[4]));
                    String imageMimeType = data.getString(data.getColumnIndexOrThrow(IMAGE_PROJECTION[5]));
                    long imageAddTime = data.getLong(data.getColumnIndexOrThrow(IMAGE_PROJECTION[6]));
                    //封装实体
                    ImageItem imageItem = new ImageItem();
                    imageItem.name = imageName;
                    imageItem.path = imagePath;
                    imageItem.size = imageSize;
                    imageItem.width = imageWidth;
                    imageItem.height = imageHeight;
                    imageItem.mimeType = imageMimeType;
                    imageItem.addTime = imageAddTime;
                    allImages.add(imageItem);
                    //根据父路径分类存放图片
                    File imageFile = new File(imagePath);
                    File imageParentFile = imageFile.getParentFile();
                    ImageFolder imageFolder = new ImageFolder();
                    imageFolder.name = imageParentFile.getName();
                    imageFolder.path = imageParentFile.getAbsolutePath();

                    if (!imageFolders.contains(imageFolder)) {
                        ArrayList<ImageItem> images = new ArrayList<>();
                        images.add(imageItem);
                        imageFolder.cover = imageItem;
                        imageFolder.images = images;
                        imageFolders.add(imageFolder);
                    } else {
                        imageFolders.get(imageFolders.indexOf(imageFolder)).images.add(imageItem);
                    }
                }
                //防止没有图片报异常
                if (data.getCount() > 0 && allImages.size() > 0) {
                    //构造所有图片的集合
                    ImageFolder allImagesFolder = new ImageFolder();
                    allImagesFolder.name = "所有图片";
                    allImagesFolder.path = "/";
                    allImagesFolder.cover = allImages.get(0);
                    allImagesFolder.images = allImages;
                    imageFolders.add(0, allImagesFolder);  //确保第一条是所有图片
                }
            }
            if (loadListener != null) {
                loadListener.loadFinish(imageFolders);
            }
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {

        }
    }

    public static void comeIn(Activity context, boolean isMulti, int maxChoose, int requestCode) {
        Intent intent = new Intent(context, ImagePickActivity.class);
        intent.putExtra(Data_isMulti, isMulti);
        intent.putExtra(Data_maxChoose, maxChoose);
        context.startActivityForResult(intent, requestCode);

    }

    public static void comeIn(Activity context, boolean isMulti, int requestCode) {
        Intent intent = new Intent(context, ImagePickActivity.class);
        intent.putExtra(Data_isMulti, isMulti);
        context.startActivityForResult(intent, requestCode);

    }

    @Override
    protected boolean isShowHeadBar() {
        return false;
    }

    @Override
    protected void initImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.statusBarColor(R.color.common_color_image_picker).fitsSystemWindows(true).init();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_activity_image_picker);
        Intent data = getIntent();
        isMulti = data.getBooleanExtra(Data_isMulti, true);
        maxChoose = data.getIntExtra(Data_maxChoose, 6);
        mImageSize = (AndroidUtil.getScreenWidth(ImagePickActivity.this)- AndroidUtil.dip2px(3 * 4)) / 3;
        initView();
        loadData();
    }

    private void loadData() {
        ImageLoad imageLoad = new ImageLoad(this, new DataLoadListener() {
            @Override
            public void loadFinish(ArrayList<ImageFolder> imageFolders) {
                allImageFolders.clear();
                allImageFolders.addAll(imageFolders);
                if (imageFolders.isEmpty()) {
                    initAdapter(null);
                } else {
                    initAdapter(allImageFolders.get(0));
                }
            }
        });
    }

    private void initView() {
        back = findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                destroyActivity();
            }
        });
        des = findViewById(R.id.des);
        enter = findViewById(R.id.enter);
        enter.setVisibility(isMulti ? View.VISIBLE : View.GONE);
        enter.setEnabled(false);
        enter.setText("确定" + "(" + 0 + "/" + maxChoose + ")");
        enter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> strings = new ArrayList<>();
                if (imageItemAdapter != null) {
                    for (ImageItem selectImage : imageItemAdapter.getSelectImages()) {
                        strings.add(selectImage.path);
                    }
                }
                Intent intent = new Intent();
                intent.putExtra(Data_selectImages, strings);
                setResult(RESULT_OK, intent);
                destroyActivity();
            }
        });
        recycler = findViewById(R.id.recycler);
        folderChooseView = findViewById(R.id.folderChooseView);
        spacer = findViewById(R.id.spacer);
        spacer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                folder.performClick();
            }
        });
        recyclerFolder = findViewById(R.id.recyclerFolder);
        bottom = findViewById(R.id.bottom);
        folder = findViewById(R.id.folder);
        folder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (folderAdapter == null) {
                    folderAdapter = new ImagePickActivity.ImageFolderAdapter(ImagePickActivity.this, allImageFolders);
                    recyclerFolder.setLayoutManager(new LinearLayoutManager(ImagePickActivity.this, LinearLayoutManager.VERTICAL, false));
                    recyclerFolder.setAdapter(folderAdapter);
                    folderAdapter.setOnclickLister(new FolderClickListener() {
                        @Override
                        public void folderClick(ImageFolder imageFolder, int pos) {
                            folderChooseView.setVisibility(View.GONE);
                            initAdapter(imageFolder);
                        }
                    });
                }
                folderAdapter.notifyDataSetChanged();
                if (folderChooseView.getVisibility() == View.VISIBLE) {
                    folderChooseView.setVisibility(View.GONE);
                } else {
                    folderChooseView.setVisibility(View.VISIBLE);
                }
            }
        });
        folderName = findViewById(R.id.folderName);
        preview = findViewById(R.id.preview);
        preview.setVisibility(isMulti ? View.VISIBLE : View.GONE);
        preview.setEnabled(false);
        preview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (imageItemAdapter != null) {
                    ArrayList<String> strings = new ArrayList<>();
                    for (ImageItem item : imageItemAdapter.getSelectImages()) {
                        strings.add(item.path);
                    }
                    ImageShowActivity.showImages(ImagePickActivity.this, strings, 0);
                }
            }
        });

    }

    private void initAdapter(ImageFolder imageFolder) {
        allImages.clear();
        if (imageFolder == null) {
            folderName.setText("全部");
        } else {
            folderName.setText(imageFolder.name);
            if (imageFolder.images != null) {
                allImages.addAll(imageFolder.images);
            }
        }
        if (imageItemAdapter == null) {
            imageItemAdapter = new ImageItemAdapter(this, isMulti, true, maxChoose, allImages);
            recycler.setLayoutManager(new GridLayoutManager(this, 3));
            GridOffsetsItemDecoration offsetsItemDecoration = new GridOffsetsItemDecoration(
                    GridOffsetsItemDecoration.GRID_OFFSETS_VERTICAL);
            offsetsItemDecoration.setVerticalItemOffsets((int) AndroidUtil.dip2px(3));
            offsetsItemDecoration.setHorizontalItemOffsets((int) AndroidUtil.dip2px(3));
            recycler.addItemDecoration(offsetsItemDecoration);
            imageItemAdapter.setImageClickListener(new ImageClickListener() {
                @Override
                public void imageClick(List<ImageItem> allImageItems, ImageItem imageItem, int pos) {
                    if (isMulti) {
                        ArrayList<String> strings = new ArrayList<>();
                        for (ImageItem item : allImageItems) {
                            strings.add(item.path);
                        }
                        ImageShowActivity.showImages(ImagePickActivity.this, strings, pos);
                    } else {
                        ArrayList<String> strings = new ArrayList<>();
                        strings.add(imageItem.path);
                        if (imageItemAdapter != null) {
                            for (ImageItem selectImage : imageItemAdapter.getSelectImages()) {
                                strings.add(selectImage.path);
                            }
                        }
                        Intent intent = new Intent();
                        intent.putExtra(Data_selectImages, strings);
                        setResult(RESULT_OK, intent);
                        destroyActivity();
                    }
                }
            });
            imageItemAdapter.setCameraClickListener(new CameraClickListener() {
                @Override
                public void cameraClick() {
                    checkPermission(Code_Permission);
                }
            });
            imageItemAdapter.setSelectChangeListener(new SelectChangeListener() {
                @Override
                public void onSelectChange(List<ImageItem> imageItems) {
                    if (imageItems.isEmpty()) {
                        enter.setEnabled(false);
                        preview.setEnabled(false);
                    } else {
                        enter.setEnabled(true);
                        preview.setEnabled(true);
                    }
                    enter.setText("确定" + "(" + imageItems.size() + "/" + maxChoose + ")");
                    preview.setText("预览" + "(" + imageItems.size() + ")");
                }
            });
            recycler.setAdapter(imageItemAdapter);
        }
        imageItemAdapter.notifyDataSetChanged();
    }

    private void checkPermission(final int requestCode) {
        if (PermissionUtils.isPermissionPass(ImagePickActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)) {
            toTake();
        } else {
            PermissionUtils.requestPermission(ImagePickActivity.this, new PermissionUtils.PermissionListener() {
                @Override
                public void onPermission(boolean isAllPass, PermissionUtils.PermissionState... permissionStates) {
                    if (isAllPass) {
                        toTake();
                    } else {
                        showPermissionDialog(requestCode, "需要外部存储，摄像头权限");
                    }
                }
            }, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA);
        }
    }

    private void toTake() {
        tempImageFile = AndroidUtil.getTempImageFile(ImagePickActivity.this);
        Uri fileUri = AndroidUtil.getFileUri(ImagePickActivity.this, tempImageFile);
        Intent captureImageIntent = AndroidUtil.getCaptureImageIntent(fileUri);
        jump2Activity(captureImageIntent, Code_Capture);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == Code_Capture) {
                if (tempImageFile.exists() && tempImageFile.isFile() && tempImageFile.canRead() && tempImageFile.length() > 0) {
                    //把拍照好的 塞到已选择列表中
                    AndroidUtil.notifyMedia(ImagePickActivity.this, tempImageFile);
                    ArrayList<String> strings = new ArrayList<>();
                    strings.add(tempImageFile.getAbsolutePath());
                    if (imageItemAdapter != null) {
                        for (ImageItem selectImage : imageItemAdapter.getSelectImages()) {
                            strings.add(selectImage.path);
                        }
                    }
                    Intent intent = new Intent();
                    intent.putExtra(Data_selectImages, strings);
                    setResult(RESULT_OK, intent);
                    destroyActivity();
                }
            }
        }
    }


    @Override
    protected void onResult4Permission(int requestCode) {
        super.onResult4Permission(requestCode);
        if (requestCode == Code_Permission) {
            checkPermission(requestCode);
        }
    }

    private class ImageItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private static final int ITEM_TYPE_CAMERA = 0;  //第一个条目是相机
        private static final int ITEM_TYPE_NORMAL = 1;  //第一个条目不是相机
        private FragmentActivity context;
        private List<ImageItem> allImages;
        private List<ImageItem> selectImages = new ArrayList<>();
        private boolean isMulti;
        private boolean isShowCamera;
        private int maxChoose;
        private ImageClickListener imageClickListener;
        private CameraClickListener cameraClickListener;
        private SelectChangeListener selectChangeListener;

        public ImageItemAdapter(FragmentActivity context, boolean isMulti, boolean isShowCamera, int maxChoose, List<ImageItem> allImages) {
            this.context = context;
            this.allImages = allImages;
            this.isMulti = isMulti;
            this.maxChoose = maxChoose;
            this.isShowCamera = isShowCamera;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            if (viewType == ITEM_TYPE_CAMERA) {
                return new CameraViewHolder(inflater.inflate(R.layout.common_item_image_picker_camera, parent, false));
            }
            return new ImageViewHolder(inflater.inflate(R.layout.common_item_image_picker_image, parent, false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            if (holder instanceof CameraViewHolder) {
                CameraViewHolder cHolder = (CameraViewHolder) holder;
                cHolder.itemView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mImageSize)); //让图片是个正方形
                cHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (selectImages.size() >= maxChoose) {
                            return;
                        }
                        if (cameraClickListener != null) {
                            cameraClickListener.cameraClick();
                        }
                    }
                });
                cHolder.itemView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mImageSize)); //让图片是个正方形

            } else if (holder instanceof ImageViewHolder) {
                ImageViewHolder iHolder = (ImageViewHolder) holder;
                int realPoi = position;
                if (isShowCamera) {
                    realPoi = position - 1;
                }
                final ImageItem item = allImages.get(realPoi);
                final int finalRealPoi = realPoi;
                iHolder.iv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isMulti) {
                            if (selectImages.contains(item)) {
                                selectImages.remove(item);
                            } else {
                                if (selectImages.size() >= maxChoose) {
                                    return;
                                }
                                selectImages.add(item);
                            }
                            if (selectChangeListener != null) {
                                selectChangeListener.onSelectChange(selectImages);
                            }
                            notifyItemChanged(position);
                        } else if (imageClickListener != null) {
                            imageClickListener.imageClick(allImages, item, finalRealPoi);
                        }
                    }
                });
                if (selectImages.contains(item)) {
                    iHolder.handler.setImageResource(R.drawable.common_image_picker_checkbox_checked);
                } else {
                    iHolder.handler.setImageResource(R.drawable.common_image_picker_checkbox_normal);
                }
                iHolder.handler.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (selectImages.contains(item)) {
                            selectImages.remove(item);
                        } else {
                            if (selectImages.size() >= maxChoose) {
                                return;
                            }
                            selectImages.add(item);
                        }
                        if (selectChangeListener != null) {
                            selectChangeListener.onSelectChange(selectImages);
                        }
                        notifyItemChanged(position);
                    }
                });
                iHolder.handler.setVisibility(isMulti ? View.VISIBLE : View.GONE);
                iHolder.itemView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mImageSize)); //让图片是个正方形
                ImageLoader.getInstance().load(context,item.path,iHolder.iv,new ImageOptions().override(mImageSize,mImageSize));
            }
        }

        @Override
        public int getItemCount() {
            if (isShowCamera) {
                return allImages.size() + 1;
            }
            return allImages.size();
        }

        @Override
        public int getItemViewType(int position) {
            if (isShowCamera) {
                return position == 0 ? ITEM_TYPE_CAMERA : ITEM_TYPE_NORMAL;
            }
            return ITEM_TYPE_NORMAL;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public List<ImageItem> getSelectImages() {
            return selectImages;
        }

        public void setImageClickListener(ImageClickListener imageClickListener) {
            this.imageClickListener = imageClickListener;
        }

        public void setCameraClickListener(CameraClickListener cameraClickListener) {
            this.cameraClickListener = cameraClickListener;
        }

        public void setSelectChangeListener(SelectChangeListener selectChangeListener) {
            this.selectChangeListener = selectChangeListener;
        }
    }

    private class ImageViewHolder extends RecyclerView.ViewHolder {
        ImageView iv;
        ImageView handler;

        public ImageViewHolder(View itemView) {
            super(itemView);
            iv = itemView.findViewById(R.id.iv);
            handler = itemView.findViewById(R.id.handler);
        }
    }

    private class CameraViewHolder extends RecyclerView.ViewHolder {
        CameraViewHolder(View itemView) {
            super(itemView);
        }
    }


    private class ImageFolderAdapter extends RecyclerView.Adapter<ImageFolderHolder> {
        private FragmentActivity context;
        private List<ImageFolder> allImageFolders;
        private FolderClickListener folderClickListener;

        public ImageFolderAdapter(FragmentActivity context, List<ImageFolder> imageFolders) {
            this.context = context;
            allImageFolders = imageFolders;
        }

        @Override
        public ImageFolderHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.common_item_image_picker_folder, parent, false);
            return new ImageFolderHolder(inflate);
        }

        @Override
        public void onBindViewHolder(ImageFolderHolder holder, final int position) {
            final ImageFolder imageFolder = allImageFolders.get(position);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (folderClickListener != null) {
                        folderClickListener.folderClick(imageFolder, position);
                    }
                }
            });
            holder.folderName.setText(imageFolder.name);
            holder.imageCount.setText("共" + imageFolder.images.size() + "张");
            ImageLoader.getInstance().load(context,imageFolder.cover.path,holder.cover,new ImageOptions().override(mImageSize,mImageSize));
        }

        @Override
        public int getItemCount() {
            return allImageFolders.size();
        }

        public void setOnclickLister(FolderClickListener folderClickListener) {
            this.folderClickListener = folderClickListener;
        }
    }

    private class ImageFolderHolder extends RecyclerView.ViewHolder {
        ImageView cover;
        TextView folderName;
        TextView imageCount;
        ImageView folderCheck;

        public ImageFolderHolder(View itemView) {
            super(itemView);
            cover = itemView.findViewById(R.id.iv_cover);
            folderName = itemView.findViewById(R.id.tv_folder_name);
            imageCount = itemView.findViewById(R.id.tv_image_count);
            folderCheck = itemView.findViewById(R.id.iv_folder_check);
        }
    }

    public interface FolderClickListener {
        void folderClick(ImageFolder imageFolder, int pos);
    }

    public interface ImageClickListener {
        void imageClick(List<ImageItem> allImageItems, ImageItem imageItem, int pos);
    }

    public interface CameraClickListener {
        void cameraClick();
    }

    public interface SelectChangeListener {
        void onSelectChange(List<ImageItem> imageItems);
    }
}
